package com.resou.reader.mine.paycenter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.api.entry.PayConfigBean;
import com.resou.reader.api.entry.WXPayBean;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.commom.Constant;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.paycenter.v.IPayView;
import com.resou.reader.paycenter.v.PayConfigItemDecoration;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.DLog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;

import static com.resou.reader.commom.Constant.WX_PAY_SUCCESS;

public class PayCenterActivity extends ResouBaseActivity<PayPresenter> implements IPayView,
        RechargePriceAdapter.OnPriceAdapterItemClickListener, PaymentMethodDialog.OnPaymentDialogInteractionListener {
    private static final String TAG = "PayCenterActivity-App";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    private IWXAPI mWXAPI;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    //    private long timestamp;
    private PayReq request = new PayReq(); //调起微信APP的对象

    /**
     * 接收微信支付成功后的广播
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(PayCenterActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
            mPresenter.getUserInfo(UserInstance.getToken());
        }
    };
    private RechargePriceAdapter mAdapter;
    private QMUITipDialog mDialog;

    @Override
    protected void initPresenter() {
        mPresenter = new PayPresenter(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    public void retryRefreshData() {
        mPresenter.loadPriceList();
    }

    @Override
    protected void initView() {
        tvTitle.setText("充值中心");
        mWXAPI = WXAPIFactory.createWXAPI(this, Constant.APP_ID_WE_CHAT, false);
        mWXAPI.registerApp(Constant.APP_ID_WE_CHAT);

        // 统计进入支付页面
        MobclickAgent.onEvent(this, "enter_pay", "进入支付页面");

        //注册微信支付的广播，以便处理相关操作
        registerReceiver(mReceiver, new IntentFilter(WX_PAY_SUCCESS));

        recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerView.addItemDecoration(new PayConfigItemDecoration());
        recyclerView.setHasFixedSize(true);
        //初始化充值价格列表
        mAdapter = new RechargePriceAdapter();
        mAdapter.setListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @Override
    public void setConfigList(List<PayConfigBean> configs) {
        mAdapter.setConfigs(configs);
    }

    @Override
    public void showLoadingIndicator() {
        mDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("加载中")
                .create();
        mDialog.show();
    }

    @Override
    public void hideLoadingIndicator() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
    }

    @Override
    public void invokeWXPay(WXPayBean wxPayBean) {
        if (wxPayBean == null) {
            DLog.d(PayCenterActivity.class.getSimpleName(), "wxPayBean == null!!");
            return;
        }

        request.appId = wxPayBean.getAppid();
        request.partnerId = wxPayBean.getMch_id();
        request.prepayId = wxPayBean.getPrepay_id();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayBean.getNonce_str();
        request.timeStamp = wxPayBean.getTimestamp();
        request.sign = wxPayBean.getSign();

        mWXAPI.sendReq(request);//发送调起微信的请求
    }

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /*
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtil.makeLongToast("支付成功");
                        mPresenter.getUserInfo(UserInstance.getToken());
                    } else if (TextUtils.equals(resultStatus, "4000")) {
                        ToastUtil.makeLongToast("支付失败");
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        ToastUtil.makeLongToast("支付取消");
                    } else if (TextUtils.equals(resultStatus, "6002")) {
                        ToastUtil.makeLongToast("网络连接出错");
                    }

//                    9000	订单支付成功
//                    8000	正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//                    4000	订单支付失败
//                    5000	重复请求
//                    6001	用户中途取消
//                    6002	网络连接出错
//                    6004	支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//                    其它	其它支付错误
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    public void invokeAliPay(String orderInfo) {
        final Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(PayCenterActivity.this);
            Map<String, String> result = alipay.payV2(orderInfo, true);
//            Log.i("msp111", result.toString());

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void sycnUserInfo() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onPaySuccess(int rechargeAmount) {
//        presenter.rechargePrice();
    }

    @Override
    public void onPayFailed(String msg) {
        Toast.makeText(this, "支付不成功，请联系客服", Toast.LENGTH_SHORT).show();
//        mPresenter.loadPriceList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorAccent));
        }
        toolbar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, PayCenterActivity.class);
        ((Activity) context).startActivityForResult(intent, Constant.PAY_REQUEST_CODE);
    }

    @Override
    public void initData() {
        mPresenter.loadPriceList();
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {
        mDialog.dismiss();
        if (throwable instanceof UnknownHostException
                || throwable instanceof UnknownServiceException
                || throwable instanceof TimeoutException || throwable instanceof ConnectException) {
            QMUITipDialog dialog = new QMUITipDialog.Builder(this)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                    .setTipWord("网络异常")
                    .create();
            dialog.show();
            mHandler.postDelayed(dialog::dismiss, 1000);
        } else {
            QMUITipDialog dialog = new QMUITipDialog.Builder(this)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                    .setTipWord("未知错误")
                    .create();
            dialog.show();
            mHandler.postDelayed(dialog::dismiss, 1000);
        }
    }

    @Override
    public void showEmpty() {
        ToastUtil.makeShortToast("网络异常");
        showNetErrorView(R.id.rlContent);
    }

    @Override
    public void onItemClicked(PayConfigBean bean) {
        if (NetworkUtils.isNetworkConnected(this)) {
            //弹起支付方式对话框
            PaymentMethodDialog payMethodDialog = PaymentMethodDialog.newInstance(bean);
            payMethodDialog.setInteractionListener(this);
            payMethodDialog.show(getSupportFragmentManager(), "payment_method_dialog");
        } else {
            ToastUtil.makeShortToast("网络异常");
        }
    }

    @Override
    public void onAliPayClicked(PayConfigBean payConfigBean) {
        if (isNetwork()) {
            mPresenter.fetchAliPayOrderInfo((int) payConfigBean.getCnyPrice());
        }
    }

    @Override
    public void onWeChatClicked(PayConfigBean payConfigBean) {
        if (isNetwork()) {
            boolean isWeChatInstall = UMShareAPI.get(ReSouApplication.getRSApplication()).isInstall(this, SHARE_MEDIA.WEIXIN);
            if (isWeChatInstall) {
                mPresenter.fetchWXOrderInfo((int) payConfigBean.getCnyPrice());
            } else {
                ToastUtil.makeShortToast("您还未安装微信");
            }
        }
    }

}
